package com.whu.helpluojia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whu.helpluojia.common.UserException;
import com.whu.helpluojia.dao.UserDao;
import com.whu.helpluojia.domain.User;
import com.whu.helpluojia.domain.dto.UserDto;
import com.whu.helpluojia.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Autowired
    UserDao userdao;

    @Resource
    RedisTemplate<String,String> redisTemplate;

    @Override
    public User getUserLogin(User user){

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        //MD5加密
        String md5Password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        queryWrapper.eq(User::getSno, user.getSno()).eq(User::getPassword, md5Password);

        User user1;
        try{
            user1=userdao.selectOne(queryWrapper);
        }catch (Exception e){
            throw new UserException(e.getMessage());
        }

        return user1;
    }

    @Override
    public User register(UserDto userdto) {

        log.info(userdto.getCode());

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getSno, userdto.getSno()).or().eq(User::getEmail,userdto.getEmail());

        User res = userdao.selectOne(queryWrapper);
        if(res != null){
            throw new UserException("已有该用户或邮箱已注册");
        }

        String code = redisTemplate.opsForValue().get(userdto.getEmail());
        if(code!=null&&code.equals(userdto.getCode())){
            userdto.setPassword(DigestUtils.md5DigestAsHex(userdto.getPassword().getBytes()));
            userdao.insert(userdto);
            return userdto;
        }

        return null;
    }

    @Override
    public User selectUser(Long userId) {
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<User>();
        qw.eq(User::getId, userId);
        return userdao.selectOne(qw);
    }

    @Override
    public User[] selectAll() {
        List<User> userList = userdao.selectList(null);
        return userList.toArray(new User[0]);
    }


}
